//
// Created by ftd on 2021/8/18.
//

#include "config/system_config.h"
#include <fstream>
#include "utils/json.hpp"


SystemConfig& SystemConfig::Instance() {
    static SystemConfig instance;
    return instance;
}

SystemConfig::SystemConfig() {

}

SystemConfig::~SystemConfig() {

}

bool SystemConfig::LoadConig() {
    std::ifstream json_file("room_oper_cfg.json", std::ifstream::in);
    if (!json_file.is_open()) {
        fprintf(stderr, "open room_oper_cfg.json fail!\n");
        return false;
    }

    nlohmann::json js;
    json_file >> js;
    json_file.close();

//    auto it = js.find("room_oper_msg");
//    if (it == js.end()) {
//        fprintf(stderr, "error: room_oper_msg key is not found, load room_oper_cfg.json fail\n");
//        return false;
//    }


    try {
        if (!js["room_oper_msg"].is_array()) {
            fprintf(stderr, "error: room_oper_msg key is not array type, load room_oper_cfg.json fail\n");
            return false;
        }
        for (auto oper_it = js["room_oper_msg"].begin(); oper_it != js["room_oper_msg"].end(); ++oper_it) {
            int msg_id = oper_it->at("msg_id");
            std::string operate_info = oper_it->at("oper_info");
            auto& cfg = room_operate_config_[msg_id];
            snprintf(cfg.operate_info, sizeof(cfg.operate_info), operate_info.c_str());
        }
        return true;
    } catch (const nlohmann::detail::out_of_range& error) {
        fprintf(stdout, "error: %s, load room_oper_cfg.json fail\n",error.what());
    } catch (const nlohmann::detail::type_error& error) {
        fprintf(stdout, "error: %s, load room_oper_cfg.json fail\n",error.what());
    }
    return false;
}
